package cn.jcet.gumall.ware.service.impl;

import cn.jcet.common.constant.WareConstant;
import cn.jcet.gumall.ware.entity.PurchaseDetailEntity;
import cn.jcet.gumall.ware.service.PurchaseDetailService;
import cn.jcet.gumall.ware.service.WareSkuService;
import cn.jcet.gumall.ware.vo.PurchaseDataVo;
import cn.jcet.gumall.ware.vo.PurchaseItemsVo;
import cn.jcet.gumall.ware.vo.PurchaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.jcet.common.utils.PageUtils;
import cn.jcet.common.utils.Query;

import cn.jcet.gumall.ware.dao.PurchaseDao;
import cn.jcet.gumall.ware.entity.PurchaseEntity;
import cn.jcet.gumall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;


    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveByPurchase(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", "0").or().eq("status", "1")
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveMergePurchase(PurchaseVo purchaseVo) {

        Long purchaseId = purchaseVo.getPurchaseId();
        if (purchaseId == null) {
            // 就创建一个新的
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseEmuns.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // TODO 采购单状态为0或者1才可以进行合并
        /**
         * 这里如果查询全部的id，根据id来操作可实现嘛？
         *
         * 如果根据采购单id可以查询嘛
         */
        List<Long> items = purchaseVo.getItems();

        List<PurchaseDetailEntity> entities = this.purchaseDetailService.listByIds(items);

//        PurchaseDetailEntity item = this.purchaseDetailService.getById(purchaseId);
//        if (!item.getStatus().equals(WareConstant.PurchaseDeatilEmuns.CREATED.getCode()) ||
//                !item.getStatus() .equals(WareConstant.PurchaseDeatilEmuns.ASSIGNED.getCode())) {
//            throw new RuntimeException("正在采购，无法合并!!!");
//        }
        Long finalPurchaseId = purchaseId;
        entities.forEach(item ->{
            if (item.getStatus().equals(WareConstant.PurchaseDeatilEmuns.CREATED.getCode()) ||
                    item.getStatus() .equals(WareConstant.PurchaseDeatilEmuns.ASSIGNED.getCode())) {
//                throw new RuntimeException("正在采购，无法合并!!!");
                // 合并操作
                List<PurchaseDetailEntity> collect = items.stream().map(ites -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(ites);
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDeatilEmuns.ASSIGNED.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
                this.purchaseDetailService.updateBatchById(collect);
            }else {
                throw new RuntimeException("正在采购，无法合并!!!");
            }
        });

        // 更新时间戳
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        // 1、处理可分配的
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity entity = this.getById(id);
            return entity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseEmuns.ASSIGNED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseEmuns.CREATED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseEmuns.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        // 改变采购单状态
        this.updateBatchById(collect);

        // 改变采购项状态
        collect.forEach(item -> {
            List<PurchaseDetailEntity> entityList = this.purchaseDetailService.listPurchaseDetailById(item.getId());
            List<PurchaseDetailEntity> collect1 = entityList.stream().map(items -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(items.getId());
                detailEntity.setStatus(WareConstant.PurchaseDeatilEmuns.BUING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            // 更新采购单信息
            this.purchaseDetailService.updateBatchById(collect1);
        });
    }

    @Override
    public void done(PurchaseDataVo purchaseDataVo) {
        // 查看状态
        Long id = purchaseDataVo.getId();

        // 查看采购清单状态
        Boolean flag = true;

        List<PurchaseItemsVo> items = purchaseDataVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemsVo item : items) {
            // 状态为失败
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDeatilEmuns.HASHERROR.getCode()){
                flag = false;
                // 设置失败状态
                detailEntity.setStatus(item.getStatus());
            }else {
                // 修改采购完成状态，添加商品到库存
                detailEntity.setStatus(WareConstant.PurchaseDeatilEmuns.FINISH.getCode());
                // 根据id查询
                PurchaseDetailEntity entity = this.purchaseDetailService.getById(item.getItemId());
                this.wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            // 添加到集合中
            updates.add(detailEntity);
        }
        // 批量修改
        this.purchaseDetailService.updateBatchById(updates);

        // 改变订单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseDeatilEmuns.FINISH.getCode(): WareConstant.PurchaseDeatilEmuns.HASHERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}